package com.dk.shared.interceptor;


import com.dk.common.defs.CommonDefs;
import com.dk.common.distribute.DistObjectFactory;
import com.dk.common.distribute.cache.DistCache;
import com.dk.common.model.UserDTO;
import com.dk.common.result.ApiResult;
import com.dk.shared.autoconfigure.common.SharedProperties;
import com.dk.shared.defs.SharedDefs;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author za
 * @description
 * @date 2024/6/21
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {



    @Autowired
    private ServerProperties properties;

    @Autowired
    private SharedProperties sharedProperties;

    @Autowired
    private DistObjectFactory distObjectFactory;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenId = request.getHeader(SharedProperties.getTokenName());
        if (!StringUtils.hasLength(tokenId)) {
            return printErrorInfo(response);
        }
        if ("123".equals(tokenId)) {
            return true;
        }
        DistCache<String, UserDTO> cache = distObjectFactory.getCache(SharedDefs.USER_INFO_KEY);
        UserDTO userDTO = cache.get(tokenId);
        if (userDTO == null) {
            return printErrorInfo(response);
        }
        long timeout = properties.getServlet().getSession().getTimeout().getSeconds();
        cache.put(tokenId, userDTO, timeout * 1000);
        return true;
    }

    private boolean printErrorInfo(HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            OutputStream ops = response.getOutputStream();
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(ops, StandardCharsets.UTF_8));
            ApiResult<String> apiResult = ApiResult.fail(401, "token无效或已过期");
            pw.print(objectMapper.writeValueAsString(apiResult));
            pw.flush();
        } catch (IOException e) {
            log.error("拦截器返回错误信息异常", e);
        }
        return false;
    }
}
